import './index.less'
import $tool from '../../common/tool.js'
import $store from '../../common/store.js'
import $ajax from '../../common/ajax.js'

$(function(){
    var g = document.createElement('script');
    g.type = 'text/javascript';
    g.async = true;
    g.defer = true;
    g.src = 'https://apis.google.com/js/api:client.js';

    var f = document.createElement('script');
    f.type = 'text/javascript';
    f.async = true;
    f.defer = true;
    // f.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v10.0&appId=249136313541020&autoLogAppEvents=1';
    f.src = 'https://connect.facebook.net/zh_TW/sdk.js';

    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(g, s);
    s.parentNode.insertBefore(f, s);
    //加载语言包
    $tool.loadProperties(res=>{
        let html = [
                'string_user_login_tip','string_user_phone','string_user_phone_code','string_user_login', 'string_request_code_sent'
            ]
        html.forEach(item=>{
            $("."+item).html($.i18n.prop(item))
        })

        $(".string_user_phone_input_tip").attr('placeholder',$.i18n.prop('string_user_phone_input_tip'))
        $(".string_user_phone_code_input_tip").attr('placeholder',$.i18n.prop('string_user_phone_code_input_tip'))
    });

    var auth2;
    // $(".header_login").on("click",function(){
    $("#header_login_id").on("click",function(){
      $(".login_main").fadeIn("fast");
      gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
            client_id: '311192923957-dklnkq4vlc0fcrncbt37v1jkkbb1qvb1.apps.googleusercontent.com', //TODO: 到Google申请的
            cookiepolicy: 'single_host_origin',
        });
    
        auth2.attachClickHandler(document.getElementById('loginG'), {}, onSuccess, onFailure);
      });

      FB.init({
        appId      : '249136313541020',
        cookie     : true,                     // Enable cookies to allow the server to access the session.
        xfbml      : true,                     // Parse social plugins on this webpage.
        version    : 'v10.0'           // Use this Graph API version for this call.
      });

      $('#loginFb').click(function(){
        FB.login(function(response){
           statusChangeCallback(response);
        });
      });
    });    

    $(".login_close").on("click",function(){
        $(".login_main").fadeOut("fast")
    })

    setTimeout(() => {
      var username = localStorage.getItem('username');
      var userId = localStorage.getItem('userId');
      if (!(username != null && username != undefined && username != '' && userId != null && userId != undefined && userId != '')) {
        var evt = document.createEvent("MouseEvents"); 
        evt.initEvent("click", true, true); 
        document.getElementById("header_login_id").dispatchEvent(evt); 
      }
    }, 500);

    codeinit()
    forminit()
    loginFb()
    loginG()
});

function forminit(){
    $("#submit").on("click",async function(){
        let name = {
            code: $.i18n.prop('string_user_phone_code_input_tip'),
            phone:$.i18n.prop('string_user_phone_input_tip'),
        }
        var formdata = {};
        var arrdata = $('#login_form').serializeArray();
        for(let item of arrdata){
            formdata[item.name] = item.value;
            if(!item.value){
                return show_err_info(name[item.name]);
            }
        }
        hide_err_info();
        let res = await $ajax.request("POST","/op/login",{
            username:formdata.phone,
            password:formdata.code,
        })
        if(res.code != 200){
            return $tool.showError(res.err||res.message||$.i18n.prop('string_request_failed'));
        }

        $store.setstate.token(res.data.sid)
        $store.setstate.userinfo(res.data)
        location.reload()
    })
}

function show_err_info(err){
    $('.err_info').html(err).show()
}
function hide_err_info(err){
    $('.err_info').hide()
}

function codeinit(){
    let time = 0;
    let t = null;
    $(".input_getcode").on("click",async function(){
        var phone = $('.input_phone').val();
        if(t){
            return
        }
        if(!phone){
            return show_err_info($.i18n.prop('string_user_phone_input_tip'));
        }
        let formdata = {
            mobile:phone
        }
        hide_err_info();
        let res = {
            code : 200
        }
        // let res = await $ajax.request("GET","",formdata)
        if(res.code != 200){
            return $tool.showError(res.err||res.message||$.i18n.prop('string_request_failed'));
        }
        $tool.showSuccess($.i18n.prop('string_request_code_sent'))
        runtime($(this))
    })

    function runtime(el){
        time = 60
        el.html(`${time}`).addClass('disabled')
        t = setInterval(function(){
            if(time==0){
                return stoptime(el);
            }
            time--
            el.html(`${time}`)
        },1000)
    }
    function stoptime(el){
        el.html($.i18n.prop('string_phone_code_button_tip')).removeClass('disabled')
        if(t){
            clearInterval(t)
            t=null;
        }
    }
}

function loginG() {}

function onSuccess(googleUser) {
  // console.log(googleUser);
  // {
  //   "Aa": "106186996154558463175",
  //   "tc": {
  //       "token_type": "Bearer",
  //       "access_token": "ya29.a0AfH6SMADErT_Rme1JjbRLKpMuNcWxA0I6PoZXqCn0LA3srcLiopcwJsQK2HbRnqYGz7l3GUqUP6VEwzopv_KRAsz8-24ovojKueDYO288DTPDJQgzE6Gfa5_SzdZmDvJtltSueiEAuNHOclpXjYELqIJU-U6",
  //       "scope": "email profile openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
  //       "login_hint": "AJDLj6JUa8yxXrhHdWRHIV0S13cAK4_DcLfKRJcMn_edfooZrvjHGp8aYh7CkWJOP3aydFZldR-JpU8FaQcXixXGRsI8tTvRLw",
  //       "expires_in": 3599,
  //       "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImUxYWMzOWI2Y2NlZGEzM2NjOGNhNDNlOWNiYzE0ZjY2ZmFiODVhNGMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMzExMTkyOTIzOTU3LWRrbG5rcTR2bGMwZmNybmNidDM3djFqa2tiYjFxdmIxLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXVkIjoiMzExMTkyOTIzOTU3LWRrbG5rcTR2bGMwZmNybmNidDM3djFqa2tiYjFxdmIxLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwic3ViIjoiMTA2MTg2OTk2MTU0NTU4NDYzMTc1IiwiZW1haWwiOiJkb2Rqb3kwM0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6IlZYR25kWkxFU1ZiaFE3UVBCYlhEaWciLCJuYW1lIjoiMDMgZG9kam95IiwicGljdHVyZSI6Imh0dHBzOi8vbGg1Lmdvb2dsZXVzZXJjb250ZW50LmNvbS8tek02QjE0bmZFYTgvQUFBQUFBQUFBQUkvQUFBQUFBQUFBQUEvQU1adXVjbnJtcnliS3FLd1JKbTdwY3pnNGtCeXc0MkNYZy9zOTYtYy9waG90by5qcGciLCJnaXZlbl9uYW1lIjoiMDMiLCJmYW1pbHlfbmFtZSI6ImRvZGpveSIsImxvY2FsZSI6InpoLUNOIiwiaWF0IjoxNjE3ODcyNzk3LCJleHAiOjE2MTc4NzYzOTcsImp0aSI6IjQxZjQ3OGUzMzM1N2Q3MjZjMDEwYTNiOWExYjIwNzFlOTMxZmRkZmYifQ.el3AZwSOhTaU0-6Ld_arktjdSq8tboyRP8JyIyvU6dsXX5ewGUuJWoCm47H0AqMjlNyaU8DQv6CMKAc1upz_Q-Oi-XlGizRdKtZ6jNifOBeKmyhTBL3kf48Mats3ejfF5jSnvvFtlekvj3e_Kz_jwd5YsRnDLWoIj77g9cZMNyHk1nV-V2HbpYwtk4p7PCQtq8WPriZxWIlLC4H9kjt0_8Wk4PE5Wlpn_juvk-g_fbKLHRr5ZpfJwEQjTDEGsL7uLdDS3XMdnlzkQdP7c_NCl13sRMqSCkPhOMwMB60jAVKnU-drG_pew1lYN58izk53J9NnUe9MiHSsK5-JQtT83Q",
  //       "session_state": {
  //           "extraQueryParams": {
  //               "authuser": "0"
  //           }
  //       },
  //       "first_issued_at": 1617872797781,
  //       "expires_at": 1617876396781,
  //       "idpId": "google"
  //   },
  //   "Rs": {
  //       "RR": "106186996154558463175",
  //       "Se": "03 dodjoy",
  //       "BT": "03",
  //       "xR": "dodjoy",
  //       "WI": "https://lh5.googleusercontent.com/-zM6B14nfEa8/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucnrmrybKqKwRJm7pczg4kByw42CXg/s96-c/photo.jpg",
  //       "At": "dodjoy03@gmail.com"
  //   }
  // }

  var authResponse = {
    userID: googleUser.Aa,
    accessToken:googleUser.tc.id_token,
  };
  login(authResponse, 8);     

  // var idToken = encodeURIComponent(googleUser.tc.id_token);
  // if (idToken) {
  //   $.ajax({
  //     url: "/php/check.php",
  //     data: {
  //       idToken: idToken
  //     },
  //     type: "get",
  //     success: function(data) {
  //       var res = JSON.parse(data);
  //       console.log(res);
  //       if (data.success == true) {
  //         var authResponse = {
  //           userID: authResponse.userID,
  //           accessToken:idToken,
  //         };
  //         login(authResponse, 8);
  //       } else {
  //         $tool.showError('please login by google!');
  //       }
  //     },
  //     error: function() {
  //       $tool.showError('please login by google!');
  //     }
  //   });
  // }
}

function onFailure(error) {
  $tool.showError('please login by google!');
}

window.fbAsyncInit = function() {
  FB.init({
    appId      : '249136313541020',
    cookie     : true,                     // Enable cookies to allow the server to access the session.
    xfbml      : true,                     // Parse social plugins on this webpage.
    version    : 'v10.0'           // Use this Graph API version for this call.
  });
  
  // FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
  //   statusChangeCallback(response);        // Returns the login status.
  // });
};

function loginFb() {}

function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
  // console.log('statusChangeCallback');
  // console.log(response);                   // The current login status of the person.
  if (response.status === 'connected') {   // Logged into your webpage and Facebook.
    // {
    //   "authResponse": {
    //       "accessToken": "EAADilpF4IZAwBAOCdTZA71BMA4HqzwdWPczfzZBZBud7kJFNLoAPATLxBdObQ5QU1i2FrGTGdg9hI3CPrNgZCii0k1qWtkiBS6ITeWkEZCLgnTqSn2Y56wc3UWEUbAhZBXk7JKQAIBUe3w80zGquY9y3gYBLoP2SjHzU94fa2svjVzxZA8kFLb2RQWNHFVq2VhkkIEed7XFfxQZDZD",
    //       "userID": "1406200653064977",
    //       "expiresIn": 7153,
    //       "signedRequest": "3OjCcffoyrBN7sWs5_NHZ87hsHDySjKaKJU3oJRqDZA.eyJ1c2VyX2lkIjoiMTQwNjIwMDY1MzA2NDk3NyIsImNvZGUiOiJBUUN6Q0dDVlhNdW1XY2NxcFhjUkZ1LVBOeW1fU2tQckZ0dnFfYzV2S2hmSFBYZ0x4dVZ1Uk9iRWUya1hGOFYyT1VqV0Q0dEhCOFBCUGlVX0FlNGRELXV6SHJxdFBaNjVWbHptZ3Z1ZjRrZGh1SW1JT1dQNW5TcUtsQ1NiZ3BYVzFjS01fYTdZQlA4T014V1lmQ3lITnhvVjZxSkpwcnQ0YWo0a19xVUt4SkNNcXBNLUxoQWpHUXRsZWRHc0VGVXkxY2NFa3AwNG8ycXhpa2t2czlpeEs3YXF3OWFOdHktVUtKdDZpbTNVZFhQazZqUFc1WkN5djNkaE9nNE94c01ZRml1RFdWZmlTRVJUcDFqX0pIYTBsaHh4ckwxMVZPWXFrQV9TdXRINGZuOTIyclhKZWxZNVRIQlVTcEZBUjN2YmozaF9GcGR2MlhvR0c1WlhvWHlDdEotSEFnejBwc3prNTI2NEJxeUFfMEgtcEEiLCJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTYxNjc1Mjg0N30",
    //       "graphDomain": "facebook",
    //       "data_access_expiration_time": 1624528847
    //   },
    //   "status": "connected"
    // }
    login(response.authResponse, 6);  
  } else {                                 // Not logged into your webpage or we are unable to tell.
    // document.getElementById('status').innerHTML = 'Please log ' + 'into this webpage.';
    $tool.showError('please login by facebook!');
  }
}

function login(authResponse, openType) {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.
  // console.log('Welcome!  Fetching your information.... ');
  const requestData = {
    userID: authResponse.userID,
    accessToken:authResponse.accessToken,
    openType: openType
  };
  $.get('/php/login.php', requestData, function(response) {
    console.log('login info: ' + response);
    
    var res = JSON.parse(response);
    if(res.status === true) {
    // {
    //   "status": true,
    //   "data": {
    //     "username": "pq40990406",
    //     "uid": "6440478",
    //     "isGuest": 0,
    //     "openType": 6,
    //     "otherAccountName": "Liu Hem",
    //     "isNewUser": 0,
    //     "bindInfo": {
    //       "bindFB": {
    //         "isBind": 1,
    //         "otherAccountName": "Liu Hem"
    //       },
    //       "bindGameCenter": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindGoogle": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindEmail": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindNaver": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindTwitter": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindLine": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindVK": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "signApple": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindPlay": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       }
    //     },
    //     "noLoginLongTime": 0,
    //     "isTrash": 0
    //   },
    //   "message": ""
    // }
      const username = res.data.username;
      const uid = res.data.uid;
      localStorage.setItem('username', username);
      localStorage.setItem('userId', uid);

      const bindinfo = res.data.bindInfo;
      const bindFB = bindinfo.bindFB;
      const bindGoogle = bindinfo.bindGoogle;

      localStorage.setItem('bindFB', JSON.stringify(bindFB));
      localStorage.setItem('bindGoogle', JSON.stringify(bindGoogle));

      $store.setstate.token(username);
      $store.setstate.userinfo(username);

      location.reload();
    } else {
      $tool.showError('login fail!');
    }
  });
}
